﻿using DG.Tweening;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
public partial class UILogin : UIBase
{
    public Button buttonRegist;
    public void onButtonRandomClick()
    {
        inputAccount.text = System.DateTime.Now.ToString("yyyyMMddHHmmss") + Random.Range(1, 1000);
        inputPassword.text = "123456";
        togglePassword.isOn = false;
    }
    public void onButtonRegistClick()
    {
        if (!IsFillAccountOrPsw())
            return;
        
        string ip = inputIp.text;
        int port;
        if (!int.TryParse(inputPort.text, out port))
        {
            Debug.LogError("can not parse port:" + port);
        }
        if (WebSocketClient.Instance.state == UnityWebSocket.WebSocketState.Open)
        {
            //onConnect2Regist();
            //return;
            WebSocketClient.Instance.Close();
        }

        buttonRegist.transform.DOScaleX(0, 0.2f);
        WebSocketClient.Instance.Connect("ws://" + ip + ":" + port, onConnect2Regist);
    }

    private void onConnect2Regist()
    {
        string account = this.inputAccount.text.Trim();
        string psw = this.inputPassword.text.Trim();
        if (string.IsNullOrEmpty(account))
        {
            Debug.LogError("account = null");
            return;
        }
        if (string.IsNullOrEmpty(psw))
        {
            Debug.LogError("psw = null");
            return;
        }
        var req = new regist();
        req.user = account;
        req.psw = psw;
        req.versioncode = CommonDefine.VersionCode;
        Debug.Log("发送 regist 消息给服务端");
        WebSocketClient.Instance.SendSerialize(req);


    }

    private void OnHandleRegistRsp(System.Object data)
    {
        buttonRegist.transform.DOKill();
        buttonRegist.transform.DOScaleX(1, 0.2f);
        var rsp = data as regist_rsp;
        if (rsp == null)
            Debug.LogError("rsp = null");
        switch (rsp.ret)
        {
            case NetErrorCode.UserExist:
                UIDialog.Instance.Show(XLocalization.Get("提示"), XLocalization.Get("注册失败。用户名已存在"), null, null);
                break;
            case NetErrorCode.None:
                this.CloseUI();
                DataPlayer.Instance.userId = rsp.reason;
                SceneMgr.Instance.LoadScene(SceneName.SceneMain);
                UITips.Instance.Show(XLocalization.Get("注册成功"));
                break;
            case NetErrorCode.VersionOld:
                UIDialog.Instance.Show(XLocalization.Get("提示"), XLocalization.Get("版本过老，请点击“确定”下载最新版本\n" + rsp.reason), () => {
                    Application.OpenURL(rsp.reason);
                }, null);
                break;
            default:
                Debug.LogError("unhandle error:" + rsp.ret);
                break;
        }
        Debug.LogFormat("服务端regist返回, result: {0}", rsp.ret + " reason:" + rsp.reason);
    }
}
